#       api_v1.py
#       
#       Copyright 2010 Alexey Zotov <alexey.zotov@gmail.com>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

# -*- coding: utf8 -*-

import json

from PyKDE4.kdecore import KUrl
from PyKDE4.kio import KIO
from PyQt4.QtCore import SIGNAL, QByteArray

BASE_URL = 'new-wallpaper.appspot.com/api/v1/'

def parse_response(job):
    if job.error():
        return None

    try:
        response = json.loads(unicode(job.data()))
    except:
        return None

    if type(response).__name__ == 'dict' and 'success' in response:
        return response

def get_response(callback, path, params, userid=None, password='',
    secure=False):

    proto = ('http://', 'https://')[secure]
    url = KUrl(proto + BASE_URL + path)
    if userid:
        if type(params).__name__ == 'dict':
            params['userid'] = userid
            params['password'] = password
        elif type(params).__name__ == 'list':
            params.append(('userid', userid))
            params.append(('password', password))
        else:
            params = {
                'userid': userid,
                'password': password
            }
    query = KUrl(url)
    if type(params).__name__ == 'dict':
        for k, v in params.iteritems():
            query.addQueryItem(k, v)
    elif type(params).__name__ == 'list':
        for k, v in params:
            query.addQueryItem(k, v)
    if userid:
        job = KIO.storedHttpPost(
            query.encodedQuery(),
            url,
            KIO.HideProgressInfo
        )
    else:
        job = KIO.storedGet(query, KIO.Reload, KIO.HideProgressInfo)
    job.result.connect(callback)

def wallpapers_info(callback, wallpapers, useronly=False, userid=None,
    password='', secure=False):

    params = [('wallpaper', wallpaper) for wallpaper in wallpapers]
    if useronly:
        params.append(('useronly', '1'))
    path = 'wallpapers/info/'
    get_response(callback, path, params, userid, password, secure)
    
def random_wallpapers(callback, count=1, resolutions=None, tags=None,
    notags=None, useronly=False, userid=None, password='', secure=False):

    params = {
        'count': str(count)
    }
    if resolutions:
        params['resolutions'] = resolutions
    if tags:
        params['tags'] = tags
    if notags:
        params['notags'] = notags
    if useronly:
        params['useronly'] = '1'
    path = 'wallpapers/random/'
    get_response(callback, path, params, userid, password, secure)

def last_wallpapers(callback, count, userid, password, secure=False):
    params = {
        'count': str(count)
    }
    path = 'wallpapers/last/'
    get_response(callback, path, params, userid, password, secure)

def new_wallpapers(callback, count, weight, userid, password, secure=False):
    params = {
        'count': str(count),
        'weight': str(weight)
    }
    path = 'wallpapers/new/'
    get_response(callback, path, params, userid, password, secure)

def add_url(callback, url, userid, password, tags=None, xmpp=False,
    secure=False):

    params = {
        'url': url
    }
    if tags:
        params['tags'] = tags
    if xmpp:
        params['xmpp'] = '1'
    path = 'add/url/'
    get_response(callback, path, params, userid, password, secure)

def add(action, callback, wallpaper, tags, userid, password, secure=False):
    params = {
        'tags': tags or ''
    }
    path = 'add/%s/%s/' % (action, wallpaper)
    get_response(callback, path, params, userid, password, secure)

def add_wallpaper(callback, wallpaper, tags, userid, password, secure=False):
    add('wallpaper', callback, wallpaper, tags, userid, password, secure)

def add_tags(callback, wallpaper, tags, userid, password, secure=False):
    add('tags', callback, wallpaper, tags, userid, password, secure)

def reject_wallpaper(callback, wallpaper, userid, password, secure=False):
    params = None
    path = 'reject/wallpaper/%s/' % wallpaper
    get_response(callback, path, params, userid, password, secure)

def send_bad_urls(callback, urls, userid, password, secure=False):
    params = [('url', url) for url in urls]
    path = 'send/bad/urls/'
    get_response(callback, path, params, userid, password, secure)

def send_duplicate(callback, original, copy, userid, password, secure=False):
    params = {
        'original': original,
        'copy': copy
    }
    path = 'send/duplicate/'
    get_response(callback, path, params, userid, password, secure)
